package com.xiaoyi.tool.http;


import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.xiaoyi.entity.XyDataQueryResult;


import org.reactivestreams.Subscriber;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.Single;
import io.reactivex.SingleEmitter;
import io.reactivex.SingleObserver;
import io.reactivex.SingleOnSubscribe;
import io.reactivex.SingleSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class XyApi {


    private static XyApi XyApi;
    private XyApiServe XyApiServe;

    private XyApi(Context context) {
        XyApiServe = HttpClient.getInstance( HostConfig.PROGRAM_IP, context).createApi(XyApiServe.class);
    }

    public static XyApi getInstance(Context context) {
        if (XyApi == null) {
            XyApi = new XyApi(context);
        }
        return XyApi;
    }



    public void  getDataDirByType(SingleObserver<ArrayList<String>> singleObserver , String mType) {
        XyApiServe.getDataDirByType( mType)
                .flatMap(new Function<ArrayList<String>, SingleSource<ArrayList<String> >>() {
                    @Override
                    public SingleSource<ArrayList<String>> apply(ArrayList<String>  list) throws Exception {
                        // 数据过滤
                        return Single.just(list);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(singleObserver)  ;
    }


    public void getDataByTypeAndDir(SingleObserver<XyDataQueryResult> singleObserver, String mType , String mDir, int pageSize, int pageNum, boolean isInverted) {
        XyApiServe.getDataByTypeAndDir( mType , mDir , pageSize, pageNum, isInverted)
                .flatMap(new Function<XyDataQueryResult, SingleSource<XyDataQueryResult>>() {
                    @Override
                    public SingleSource<XyDataQueryResult> apply(XyDataQueryResult XyDataPagerQueryResult) throws Exception {
                        return Single.just(XyDataPagerQueryResult);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(singleObserver)  ;
    }


    public void loadLrcByUrl(SingleObserver<String> singleObserver,String lrcUrl  ) {
        getTxtFromUrl(lrcUrl )
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(singleObserver)  ;
    }




    public Single<String >  getTxtFromUrl( final String lrcUrl ){

       return  Single.create(new SingleOnSubscribe<String>() {
           @Override
           public void subscribe(SingleEmitter<String> emitter) throws Exception {
               String reslult = getTxtFromUrl0(lrcUrl) ;
               emitter.onSuccess(reslult);
           }
       });
    }

    private String getTxtFromUrl0(String path){
        String lrcText = null;
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setReadTimeout(10000);

            if (conn.getResponseCode() == 200) {
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()  , "gb2312"));
                StringBuilder sb = new StringBuilder();
                String line;
                while (null != (line = br.readLine())) {
//                    line = new String( line.getBytes("GBK") , "GBK");
                    sb.append(line);
                    sb.append("\r\n");
                }
                lrcText = sb.toString();
                br.close();
                conn.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return lrcText;
    }

}
